package com.taotao.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taotao.entity.Book;
import com.taotao.service.BookService;
import com.taotao.service.CategoryService;
import com.taotao.vo.BookVO;
import com.taotao.vo.PageResult;
import com.taotao.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
public class BookController {
    @Autowired
    private BookService bookService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("getBooksPage")
    public Result getBooksPage(@RequestParam(value = "pageNo") Long pageNo,
                                   @RequestParam(value = "pageSize") Long pageSize) {
        Page<Book> page = bookService.page(new Page(pageNo, pageSize));

        List<BookVO> bookVOList = CollUtil.newArrayList();
        for (Book book : page.getRecords()) {
            BookVO bookVO = BeanUtil.copyProperties(book, BookVO.class);
            bookVO.setCategory(categoryService.getById(book.getCategoryId()));
            bookVOList.add(bookVO);
        }

        return new Result().setCode(0).setMsg("success").setData(new PageResult().setTotal(page.getTotal()).setRecords(bookVOList));
    }

    @PostMapping("addBook")
    public Result addBook(@RequestBody Book book) {
        bookService.save(book);
        return new Result().setCode(0).setMsg("success");
    }

    @DeleteMapping("delete")
    public Result delete(Integer bookId) {
        bookService.removeById(bookId);
        return new Result().setCode(0).setMsg("success");
    }

    @DeleteMapping("batchDelete")
    public Result batchDelete(@RequestBody List<Integer> bookIdList) {
        bookService.removeBatchByIds(bookIdList);
        return new Result().setCode(0).setMsg("success");
    }
}
